package logic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2653629499720914101L;
	private String id;
	private String name;
	private boolean isOffline;
	private String courseId;
	private List<Question> questions;

	/* Data base fields */
	public static final String KEY_ID = "test_id";
	public static final String KEY_NAME = "name";
	public static final String COURSE_KEY = "course_key";
	public static final String KEY_TIMESTAMP = "time_stamp";

	public Test(String id, String testName, boolean isOffline, String courseId) {
		this.id = id;
		this.name = testName;
		this.isOffline = isOffline;
		this.courseId = courseId;
	}

	public Test(String id, String testName, List<Question> questions,
			boolean isOffline) {
		this.id = id;
		this.name = testName;
		this.questions = questions;
		this.isOffline = isOffline;
	}

	public Test(String testName, List<Question> questions) {
		this.name = testName;
		this.questions = questions;
	}

	public boolean isOffline() {
		return isOffline;
	}

	public List<Question> getQuestions() {
		return questions;
	}

	public String getName() {
		return name;
	}

	public String getId() {
		return id;
	}

	public void setQuesions(List<Question> questions) {
		this.questions = questions;
	}

	public static List<Test> getTestsFromJSON(String json) {
		ArrayList<Test> Tests = new ArrayList<Test>();
		try {
			JSONArray jsonArray = new JSONArray(json);
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				String id = jsonObject.getString("id_test");
				String name = jsonObject.getString("nombre");
				String course = jsonObject.getString("id_asig");

				Tests.add(new Test(id, name, false, course));
			}
			return Tests;
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static Test getSingleTestFromJSON(String json) {
		try {
			JSONObject jsonObj = new JSONObject(json);
//			JSONArray jsonArray = new JSONArray(json);
//			for (int i = 0; i < jsonArray.length(); i++) {
//				JSONObject jsonObject = getJSONObject(i);
				String id = jsonObj.getString("id_test");
				String name = jsonObj.getString("nombre");
				String course = jsonObj.getString("id_asig");

				return new Test(id, name, false, course);
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	public void switchOffline() {
		this.isOffline = !isOffline;
	}
}
